package com.tedu.bill.demo2;

/**
 * Author：毕龙
 * Date: 2024/5/19 9:13
 */
public class MyLinked {
    //表示第一个链表元素
    private Node first;
    //表示链表的下标 模拟链表中的下标
    private int index;


    //声明一个内部类
    class Node{
        private Object data;
        private Node next;

        public Node() {
        }

        public Node(Object data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    //向链表中添加一个元素
    public void add(Object data){
        //index==0链表中还没有元素
        if(index == 0){
            first = new Node(data,null);
            index ++;
        }else{
            /*//先将first保存起来
            Node node = first;
            node.next = new Node(data,null);
            index++;*/
           Node node = first;
            for (int i = 1; i < index; i++) {
                node = node.next;
            }
            node.next = new Node(data,null);
            index ++;
        }
    }

    //遍历链表
    public Object get(int indexLinked){
        if(index < indexLinked){
            throw new IndexOutOfBoundsException("index:"+index +"  indexLined:"+indexLinked);
        }
        Node node = first;
        for (int i = 1; i < indexLinked; i++) {
            node = node.next;
        }
        return node.data;
    }


    public void forEach(){
        Node node = first;
        System.out.println(node.data);
        for (int i = 1; i < index; i++) {
            node = node.next;
            System.out.println(node.data);
        }
    }


    public void add(Object data,int position){
        if(position >  index){
            throw new IndexOutOfBoundsException("index:"+index +"  position:"+position);
        }
        //遍历该node
        Node node = first;
        for (int i = 1; i < position; i++) {
            node = node.next;
        }
        //使用that将node的下一个元素保存起来
        Node that = node.next;
        //将node的下一个元素改变为新的node
        node.next = new Node(data,that);
        index ++;
    }



    public void remove(int indexDelete){
        if(indexDelete >  index){
            throw new IndexOutOfBoundsException("index:"+index +"  indexDelete:"+indexDelete);
        }

        if(indexDelete == 0){
            first = first.next;
            index --;
            return;
        }

        //遍历该node
        Node node = first;
        //是获取要删除的node的上一个node
        for (int i = 1; i < indexDelete-1; i++) {
            node = node.next;
        }
        if(node.next.next==null){
            node.next = null;
            index --;
            return;
        }
        //获取下一个node
        Node that = node.next.next;
        //将上一个node的下一个值活成下下node
        node.next = that;
        index --;

    }

}
